import Layout from '@/layout'
import UpmsRoutersApi from '@/api/upms/routers'
import { pidToChildren } from '@/utils/tree'
import { constantRoutes } from '@/router'

const state = {
  routes: [],
  addRoutes: []
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routes = constantRoutes.concat(routes)
  }
}

export const loadView = view => {
  return resolve => require(['@/views/' + view], resolve)
}

function hasPermission(roles, route) {
  if (route.meta && route.meta.permission) {
    return roles.some(role => route.meta.permission === role)
  } else {
    return true
  }
  // return true
}

export function filterAsyncRoutes(routes, roles) {
  const res = []
  routes.forEach(route => {
    const tmp = { ...route }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}
function buildChildren(children) {
  if (children) {
    return children.map(m => {
      return {
        path: m.path,
        component: (m.component === 'Layout' ? Layout : loadView(m.component)),
        name: m.code,
        meta: { title: m.metaTitle, permission: m.code },
        children: buildChildren(m.children)
      }
    })
  }
  return []
}

const actions = {
  generateRoutes({ commit }, roles) {
    return new Promise((resolve, reject) => {
      UpmsRoutersApi.page({
        baseParams: {},
        sort: 'seq asc'
      }).then(({ data }) => {
        let routers = pidToChildren(data.filter(row => ['module', 'page'].indexOf(row.type) > -1), {}, false)
        routers = routers.map(m => {
          return {
            path: m.path,
            component: (m.component === 'Layout' ? Layout : loadView(m.component)),
            name: m.code,
            meta: { title: m.metaTitle, permission: m.code, icon: m.icon },
            redirect: m.redirect,
            children: buildChildren(m.children),
            alwaysShow: true
          }
        })

        routers = filterAsyncRoutes(routers, roles)
        routers = routers.concat({ path: '*', redirect: '/404', hidden: true })
        commit('SET_ROUTES', routers)
        resolve(routers)
      })
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
